package com.shanwen.shopping.adapter;

import android.app.Activity;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

import com.classic.core.utils.DataUtil;
import com.shanwen.shopping.activity.WebViewActivity;
import com.shanwen.shopping.entity.BannerInfo;

import java.util.List;

/**
 * Created by lex on 2017/9/27.
 */

public class BannerAdapter extends PagerAdapter {

    private List<View> viewList;
    private int size;
    private final int cacheCount = 3;
    private List<BannerInfo> mBannerList;
    private Activity context;

    public BannerAdapter(Activity context, List<View> viewList, List<BannerInfo> mBannerList) {
        this.context = context;
        this.viewList = viewList;
        this.mBannerList = mBannerList;
        size = viewList.size();
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        if (viewList.size() > cacheCount){
            container.removeView(viewList.get(position%size));
        }
    }

    @Override
    public Object instantiateItem(final ViewGroup container, final int position) {
        ViewGroup parent = (ViewGroup) viewList.get(position%size).getParent();
        if (parent != null) {
            parent.removeView(viewList.get(position%size));
        }
        container.addView(viewList.get(position%size));
        viewList.get(position%size).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BannerInfo info = mBannerList.get(position%size);
                switch (info.getType()) {
                    case BannerInfo.TYPE_BANNER:

                        break;
                    case BannerInfo.TYPE_BOOKS:

                        break;
                    case BannerInfo.TYPE_BOOKSURL:
                        break;
                    case BannerInfo.TYPE_URL:
                    case BannerInfo.TYPE_UR2:
                        WebViewActivity.start(context,
                                DataUtil.isEmpty(info.getBannerName()) ? "" : info.getBannerName(),
                                info.getContent());
                        break;
                }
            }
        });
        return viewList.get(position%size);
    }

    @Override
    public int getCount() {
        return Integer.MAX_VALUE;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }
}